package com.smart.translator.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.util.DisplayMetrics;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.smart.translator.R;
import com.smart.translator.ui.MessageAdapter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
import android.speech.tts.TextToSpeech;
import android.media.AudioManager;
import java.util.Locale;
import android.widget.Toast;
// import com.smart.translator.util.SimpleTtsEngine;
import com.smart.translator.util.SimpleWebSocketTTSPlayer;
import com.smart.translator.util.UserManager;
import com.smart.translator.data.StatsApiService;
import com.smart.translator.data.ApiResponse;
import java.util.concurrent.CompletableFuture;
import android.os.Handler;
import android.os.Looper;

public class FloatWindowService extends Service {
    private WindowManager windowManager;
    private View floatView;
    private WindowManager.LayoutParams params;
    private float lastX, lastY;
    private boolean isMoving = false;

    // Tab和内容区引用
    private TextView tab1, tab2, tab3;
    private View content1, content2, content3, inputArea;

    // 新增消息相关变量
    private java.util.List<MessageAdapter.Message> messageList = new java.util.ArrayList<>();
    private MessageAdapter messageAdapter;
    private RecyclerView recyclerView;

    // 1. 新增Tab3（语音转文本）相关成员变量
    private java.util.List<MessageAdapter.Message> messageListVosk = new java.util.ArrayList<>();
    private MessageAdapter messageAdapterVosk;
    private RecyclerView recyclerViewVosk;
    private LinearLayout layoutPeerSpeakingVosk;
    private int currentMsgIndexVosk = -1;
    private boolean isPeerSpeakingVosk = false;

    // 在类成员变量区域添加
    private static final String LANG_CACHE_KEY = "allLanguages";
    private static final String PREFS_NAME = "home_prefs";
    private static final String OTHER_LANG_INDEX_KEY = "otherLangIndex";
    private static final String MY_LANG_INDEX_KEY = "myLangIndex";
    private SharedPreferences homePrefs;
    
    // 广播接收器
    private BroadcastReceiver asrReceiver;

    // 新增：对方VAD说话状态
    private boolean isPeerSpeaking = false;
    private int currentMsgIndex = -1;
    private String lastAsrText = ""; // 记录本段ASR最新内容
    private String lastFinalAsrText = ""; // 记录上一次VAD段落最终内容
    private String lastAliyunAsrText = ""; // 记录上一次阿里云ASR结果，防止重复处理
    private LinearLayout layoutPeerSpeaking;

    // 新增：TTS状态显示
    private LinearLayout layoutTtsPlaying;
    private TextView tvTtsPlaying;
    private boolean isTtsPlaying = false;
    private String currentTtsText = "";

    // 1. 在FloatWindowService类中添加回调接口
    public interface TranslateCallback {
        void onResult(String result);
    }

    // TTS引擎 - 暂时注释掉，不需要TTS功能
    // private SimpleTtsEngine simpleTtsEngine;
    private SimpleWebSocketTTSPlayer ttsPlayer;

    // 新增：Tab1智能断句状态
    private boolean isCloudFinalTab1 = false;
    private boolean isVadSilentTab1 = false;
    private long lastAsrUpdateTimeTab1 = 0;
    private static final long ASR_WAIT_TIMEOUT = 5000; // 5秒超时兜底
    private Handler asrWaitHandlerTab1 = new Handler(Looper.getMainLooper());
    private Runnable asrWaitRunnableTab1;

    // 新增：悬浮窗控制广播接收器
    private BroadcastReceiver floatWindowControlReceiver;
    private boolean isFloatWindowShown = false;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("FloatWindowService", "onCreate: 悬浮窗服务已启动");

        try {
            windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
            LayoutInflater inflater = LayoutInflater.from(this);
            floatView = inflater.inflate(R.layout.float_window, null);
            Log.d("FloatWindowService", "悬浮窗视图已创建");

            // 获取屏幕高度，设置悬浮窗高度为屏幕高度的50%
            DisplayMetrics dm = new DisplayMetrics();
            windowManager.getDefaultDisplay().getMetrics(dm);
            int windowHeight = (int) (dm.heightPixels * 0.5f);

            int type = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ?
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY :
                    WindowManager.LayoutParams.TYPE_PHONE;
            params = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    windowHeight, // 固定高度为屏幕70%
                    type,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                    PixelFormat.TRANSLUCENT
            );
            params.gravity = Gravity.CENTER;
            Log.d("FloatWindowService", "悬浮窗参数已设置");

            // Tab和内容区初始化
            tab1 = floatView.findViewById(R.id.tab_voice_free);
            // 暂时注释掉Tab2的初始化
            // tab2 = floatView.findViewById(R.id.tab_voice_normal);
            tab3 = floatView.findViewById(R.id.tab_text);
            content1 = floatView.findViewById(R.id.float_content_tab1);
            // 暂时注释掉Tab2内容区的初始化
            // content2 = floatView.findViewById(R.id.float_content_tab2);
            content3 = floatView.findViewById(R.id.float_content_tab3);
            inputArea = floatView.findViewById(R.id.float_input_area);
            Log.d("FloatWindowService", "Tab和内容区已初始化");

            tab1.setOnClickListener(v -> switchTab(0));
            // 暂时注释掉Tab2的点击事件
            // tab2.setOnClickListener(v -> switchTab(1));
            tab3.setOnClickListener(v -> switchTab(1)); // 调整为switchTab(1)
            switchTab(0); // 默认显示第一个Tab

            // 拖动逻辑
            floatView.setOnTouchListener((v, event) -> {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        lastX = event.getRawX();
                        lastY = event.getRawY();
                        isMoving = false;
                        return false;
                    case MotionEvent.ACTION_MOVE:
                        float dx = event.getRawX() - lastX;
                        float dy = event.getRawY() - lastY;
                        if (Math.abs(dx) > 10 || Math.abs(dy) > 10) {
                            params.x += dx;
                            params.y += dy;
                            windowManager.updateViewLayout(floatView, params);
                            lastX = event.getRawX();
                            lastY = event.getRawY();
                            isMoving = true;
                            return true;
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        if (isMoving) return true;
                        break;
                }
                return false;
            });

            // 关闭按钮
            ImageView closeBtn = floatView.findViewById(R.id.float_close_btn);
            closeBtn.setOnClickListener(v -> {
                // 发送广播通知设置界面更新悬浮窗开关状态
                Intent intent = new Intent("com.smart.translator.FLOAT_WINDOW_CLOSED");
                LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
                sendFloatWindowStatusBroadcast(false);
                stopSelf();
            });

            // RecyclerView初始化
            recyclerView = floatView.findViewById(R.id.message_list);
            messageAdapter = new MessageAdapter(messageList);
            recyclerView.setAdapter(messageAdapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            
            // 性能优化设置
            recyclerView.setHasFixedSize(true);
            recyclerView.setItemViewCacheSize(20);
            recyclerView.setDrawingCacheEnabled(true);
            recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
            
            Log.d("FloatWindowService", "RecyclerView已初始化");

            // 发送按钮
            Button sendBtn = floatView.findViewById(R.id.float_send_btn);
            EditText inputEdit = floatView.findViewById(R.id.float_input_edit);
            sendBtn.setOnClickListener(v -> {
                String text = inputEdit.getText().toString().trim();
                if (!text.isEmpty() && text.length() > 1) { // 至少2个字符
                    // 添加空指针检查
                    if (messageAdapter == null) {
                        Log.w("FloatWindowService", "messageAdapter为null，跳过消息发送");
                        return;
                    }
                    
                    // 检查是否与最后一条用户消息重复
                    if (!messageList.isEmpty()) {
                        MessageAdapter.Message lastMessage = messageList.get(messageList.size() - 1);
                        if (lastMessage.isMe && lastMessage.sourceText.equals(text)) {
                            Log.d("FloatWindowService", "跳过重复的用户消息: " + text);
                            inputEdit.setText("");
                            return;
                        }
                    }
                    
                    // 显示用户输入的消息
                    MessageAdapter.Message msg = new MessageAdapter.Message(true, text, "");
                    messageList.add(msg);
                    int pos = messageList.size() - 1;
                    messageAdapter.notifyItemInserted(pos);
                    recyclerView.scrollToPosition(pos);
                    inputEdit.setText("");
                    
                    sendTTSText(text);
                    // 上传统计数据
                    uploadTtsStats(text.length());
                 
                    // // 调用TTS合成语音
                    // if (ttsPlayer != null && ttsPlayer.isConnected()) {
                    //     // Tab1（无障碍通话）：自动选择音频输出模式（耳机优先）
                    //     ttsPlayer.setAudioOutputMode(SimpleWebSocketTTSPlayer.AUDIO_OUTPUT_AUTO);
                    //     ttsPlayer.sendText(text);
                        
                    //     // 上传统计数据
                    //     uploadTtsStats(text.length());
                    // } else {
                    //     Toast.makeText(this, "TTS未连接", Toast.LENGTH_SHORT).show();
                    // }



                         // 检查TTS连接状态，如果断开则重新连接
                        //  if (ttsPlayer != null) {
                        //     if (!ttsPlayer.isConnected()) {
                        //         Log.d("FloatWindowService", "TTS WebSocket已断开，重新连接");
                        //         ttsPlayer.connect();
                                
                        //         // 延迟发送文本，等待连接完成，增加重试机制
                        //         new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(new Runnable() {
                        //             private int retryCount = 0;
                        //             private final int maxRetries = 10; // 最多重试10次
                        //             private final int retryInterval = 500; // 每次间隔500ms
                                    
                        //             @Override
                        //             public void run() {
                        //                 if (ttsPlayer.isConnected()) {
                        //                     Log.d("FloatWindowService", "TTS重新连接成功，发送文本: " + text);
                        //                     // Tab3（语音转文字）：强制使用扬声器
                        //                     ttsPlayer.setAudioOutputMode(SimpleWebSocketTTSPlayer.AUDIO_OUTPUT_AUTO);
                        //                     ttsPlayer.sendText(text);
                                            
                        //                     // 上传统计数据
                        //                     uploadTtsStats(text.length());
                        //                 } else if (retryCount < maxRetries) {
                        //                     retryCount++;
                        //                     Log.d("FloatWindowService", "TTS连接检查失败，重试第" + retryCount + "次");
                        //                     new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(this, retryInterval);
                        //                 } else {
                        //                     Log.w("FloatWindowService", "TTS重新连接失败，无法发送文本: " + text);
                        //                     Toast.makeText(FloatWindowService.this, "TTS连接失败", Toast.LENGTH_SHORT).show();
                        //                 }
                        //             }
                        //         }, 2000); // 延迟2秒开始检查
                        //     } else {
                        //         // TTS已连接，直接发送
                        //         Log.d("FloatWindowService", "TTS已连接，直接发送文本: " + text);
                        //         // Tab3（语音转文字）：强制使用扬声器
                        //         ttsPlayer.setAudioOutputMode(SimpleWebSocketTTSPlayer.AUDIO_OUTPUT_AUTO);
                        //         ttsPlayer.sendText(text);
                                
                        //         // 上传统计数据
                        //         uploadTtsStats(text.length());
                        //     }
                        // } else {
                        //     Log.w("FloatWindowService", "TTS播放器为null，无法发送文本");
                        //     Toast.makeText(this, "TTS未初始化", Toast.LENGTH_SHORT).show();
                        // }
                        
                    Log.d("FloatWindowService", "无障碍通话界面发送用户消息: " + text);
                  
                    
                    // Log.d("FloatWindowService", "发送用户消息: " + text);
                    
                    // 注释掉翻译逻辑
                    // translateAsync(text, result -> {
                    //     messageList.get(pos).translatedText = result;
                    //     messageAdapter.notifyItemChanged(pos);
                    // });
                } else if (text.length() <= 1) {
                    Log.d("FloatWindowService", "消息太短，忽略: " + text);
                }
            });

            // 输入框点击时，移除FLAG_NOT_FOCUSABLE并弹出键盘
            inputEdit.setOnTouchListener((v, event) -> {
                if ((params.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) != 0) {
                    params.flags &= ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
                    windowManager.updateViewLayout(floatView, params);
                    inputEdit.requestFocus();
                    android.os.Handler handler = new android.os.Handler(android.os.Looper.getMainLooper());
                    handler.postDelayed(() -> {
                        android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        if (imm != null) {
                            imm.showSoftInput(inputEdit, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT);
                        }
                    }, 100);
                }
                return false;
            });
            // 输入框失去焦点时，加回FLAG_NOT_FOCUSABLE
            inputEdit.setOnFocusChangeListener((v, hasFocus) -> {
                if (!hasFocus) {
                    params.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
                    windowManager.updateViewLayout(floatView, params);
                }
            });

            // 在onCreate()方法中，在初始化RecyclerView后添加
            homePrefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            Log.d("FloatWindowService", "SharedPreferences已初始化");
            
            // 注册ASR结果广播接收器
            registerAsrReceiver();
            Log.d("FloatWindowService", "ASR结果广播接收器已注册");

            // 新增：对方VAD说话状态
            layoutPeerSpeaking = floatView.findViewById(R.id.layout_peer_speaking);
            setPeerSpeaking(false);

            // 新增：TTS状态显示初始化
            layoutTtsPlaying = floatView.findViewById(R.id.layout_tts_playing);
            tvTtsPlaying = floatView.findViewById(R.id.tv_tts_playing);
            setTtsPlaying(false, "");

            // 注册VAD说话状态广播
            registerVadStateReceiver();
            
            // 注册Vosk VAD说话状态广播
            registerVoskVadStateReceiver();

            // TTS初始化 - WebSocket TTS
            ttsPlayer = new SimpleWebSocketTTSPlayer(this);
            ttsPlayer.setTTSStateCallback(new SimpleWebSocketTTSPlayer.TTSStateCallback() {
                @Override
                public void onTTSStart(String text) {
                    setTtsPlaying(true, text);
                }

                @Override
                public void onTTSEnd(String text) {
                    setTtsPlaying(false, "");
                }
            });
            ttsPlayer.connect();
            Log.d("FloatWindowService", "SimpleWebSocketTTSPlayer已初始化并连接");

            // Tab3相关控件初始化
            recyclerViewVosk = floatView.findViewById(R.id.message_list_vosk);
            messageAdapterVosk = new MessageAdapter(messageListVosk);
            recyclerViewVosk.setAdapter(messageAdapterVosk);
            recyclerViewVosk.setLayoutManager(new LinearLayoutManager(this));
            
            // Tab3性能优化设置
            recyclerViewVosk.setHasFixedSize(true);
            recyclerViewVosk.setItemViewCacheSize(20);
            recyclerViewVosk.setDrawingCacheEnabled(true);
            recyclerViewVosk.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
            
            layoutPeerSpeakingVosk = floatView.findViewById(R.id.layout_peer_speaking_vosk);
            setPeerSpeakingVosk(false);
            EditText inputEditVosk = floatView.findViewById(R.id.float_input_edit_vosk);
            Button sendBtnVosk = floatView.findViewById(R.id.float_send_btn_vosk);
            LinearLayout inputAreaVosk = floatView.findViewById(R.id.float_input_area_vosk);
            // 输入框点击时弹出键盘
            inputEditVosk.setOnTouchListener((v, event) -> {
                if ((params.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) != 0) {
                    params.flags &= ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
                    windowManager.updateViewLayout(floatView, params);
                    inputEditVosk.requestFocus();
                    android.os.Handler handler = new android.os.Handler(android.os.Looper.getMainLooper());
                    handler.postDelayed(() -> {
                        android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        if (imm != null) {
                            imm.showSoftInput(inputEditVosk, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT);
                        }
                    }, 100);
                }
                return false;
            });
            // 输入框失去焦点时，加回FLAG_NOT_FOCUSABLE
            inputEditVosk.setOnFocusChangeListener((v, hasFocus) -> {
                if (!hasFocus) {
                    params.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
                    windowManager.updateViewLayout(floatView, params);
                }
            });
            // 发送按钮：暂时无TTS处理逻辑
            sendBtnVosk.setOnClickListener(v -> {
                String text = inputEditVosk.getText().toString().trim();
                if (!text.isEmpty() && text.length() > 1) { // 至少2个字符
                    // 添加空指针检查
                    if (messageAdapterVosk == null) {
                        Log.w("FloatWindowService", "messageAdapterVosk为null，跳过消息发送");
                        return;
                    }
                    
                    // 检查是否与最后一条用户消息重复
                    if (!messageListVosk.isEmpty()) {
                        MessageAdapter.Message lastMessage = messageListVosk.get(messageListVosk.size() - 1);
                        if (lastMessage.isMe && lastMessage.sourceText.equals(text)) {
                            Log.d("FloatWindowService", "跳过重复的用户消息: " + text);
                            inputEditVosk.setText("");
                            return;
                        }
                    }
                    
                    // 显示用户输入的消息
                    MessageAdapter.Message msg = new MessageAdapter.Message(true, text, "");
                    messageListVosk.add(msg);
                    int pos = messageListVosk.size() - 1;
                    messageAdapterVosk.notifyItemInserted(pos);
                    recyclerViewVosk.scrollToPosition(pos);
                    inputEditVosk.setText("");
                    
                    // 检查TTS连接状态，如果断开则重新连接
                    if (ttsPlayer != null) {
                        if (!ttsPlayer.isConnected()) {
                            Log.d("FloatWindowService", "TTS WebSocket已断开，重新连接");
                            ttsPlayer.connect();
                            
                            // 延迟发送文本，等待连接完成，增加重试机制
                            new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(new Runnable() {
                                private int retryCount = 0;
                                private final int maxRetries = 10; // 最多重试10次
                                private final int retryInterval = 500; // 每次间隔500ms
                                
                                @Override
                                public void run() {
                                    if (ttsPlayer.isConnected()) {
                                        Log.d("FloatWindowService", "TTS重新连接成功，发送文本: " + text);
                                        // Tab3（语音转文字）：强制使用扬声器
                                        ttsPlayer.setAudioOutputMode(SimpleWebSocketTTSPlayer.AUDIO_OUTPUT_SPEAKER);
                                        ttsPlayer.sendText(text);
                                        
                                        // 上传统计数据
                                        uploadTtsStats(text.length());
                                    } else if (retryCount < maxRetries) {
                                        retryCount++;
                                        Log.d("FloatWindowService", "TTS连接检查失败，重试第" + retryCount + "次");
                                        new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(this, retryInterval);
                                    } else {
                                        Log.w("FloatWindowService", "TTS重新连接失败，无法发送文本: " + text);
                                        Toast.makeText(FloatWindowService.this, "TTS连接失败", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }, 2000); // 延迟2秒开始检查
                        } else {
                            // TTS已连接，直接发送
                            Log.d("FloatWindowService", "TTS已连接，直接发送文本: " + text);
                            // Tab3（语音转文字）：强制使用扬声器
                            ttsPlayer.setAudioOutputMode(SimpleWebSocketTTSPlayer.AUDIO_OUTPUT_SPEAKER);
                            ttsPlayer.sendText(text);
                            
                            // 上传统计数据
                            uploadTtsStats(text.length());
                        }
                    } else {
                        Log.w("FloatWindowService", "TTS播放器为null，无法发送文本");
                        Toast.makeText(this, "TTS未初始化", Toast.LENGTH_SHORT).show();
                    }
                    
                    Log.d("FloatWindowService", "发送用户消息: " + text);
                } else if (text.length() <= 1) {
                    Log.d("FloatWindowService", "消息太短，忽略: " + text);
                }
            });

            windowManager.addView(floatView, params);
            isFloatWindowShown = true;
            Log.d("FloatWindowService", "悬浮窗已添加到窗口管理器");
            sendFloatWindowStatusBroadcast(true);
            
        } catch (Exception e) {
            Log.e("FloatWindowService", "onCreate方法出现异常", e);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("FloatWindowService", "onStartCommand: 悬浮窗服务收到启动命令");
        return super.onStartCommand(intent, flags, startId);
    }

    private void switchTab(int index) {
        tab1.setBackgroundResource(index == 0 ? R.drawable.bg_tab_selected : R.drawable.bg_tab_unselected);
        // 暂时注释掉Tab2的处理
        // tab2.setBackgroundResource(index == 1 ? R.drawable.bg_tab_selected : R.drawable.bg_tab_unselected);
        tab3.setBackgroundResource(index == 1 ? R.drawable.bg_tab_selected : R.drawable.bg_tab_unselected); // 调整为index == 1
        content1.setVisibility(index == 0 ? View.VISIBLE : View.GONE);
        // 暂时注释掉Tab2内容区的处理
        // content2.setVisibility(index == 1 ? View.VISIBLE : View.GONE);
        content3.setVisibility(index == 1 ? View.VISIBLE : View.GONE); // 调整为index == 1
        inputArea.setVisibility(index == 0 ? View.VISIBLE : View.GONE);
        LinearLayout inputAreaVosk = floatView.findViewById(R.id.float_input_area_vosk);
        inputAreaVosk.setVisibility(index == 1 ? View.VISIBLE : View.GONE); // 调整为index == 1
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("FloatWindowService", "onDestroy: 悬浮窗服务销毁");
        sendFloatWindowStatusBroadcast(false);
        
        // 注销LocalBroadcastManager接收器
        if (asrReceiver != null) {
            try {
                LocalBroadcastManager.getInstance(this).unregisterReceiver(asrReceiver);
                Log.d("FloatWindowService", "LocalBroadcastManager ASR接收器已注销");
            } catch (Exception e) {
                Log.e("FloatWindowService", "注销LocalBroadcastManager ASR接收器失败", e);
            }
            asrReceiver = null;
        }
        
        // 移除悬浮窗
        if (windowManager != null && floatView != null && isFloatWindowShown) {
            try {
                windowManager.removeView(floatView);
                isFloatWindowShown = false;
                Log.d("FloatWindowService", "悬浮窗已移除");
            } catch (Exception e) {
                Log.e("FloatWindowService", "移除悬浮窗失败", e);
            }
        }
        
        // 清理资源
        if (messageAdapter != null) {
            messageAdapter = null;
        }
        // TTS资源释放 - 暂时注释掉，不需要TTS功能
        if (ttsPlayer != null) {
            ttsPlayer.disconnect();
            ttsPlayer = null;
        }
        if (floatWindowControlReceiver != null) {
            unregisterReceiver(floatWindowControlReceiver);
            floatWindowControlReceiver = null;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public static void requestAndShowFloatWindow(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(context)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + context.getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } else {
                context.startService(new Intent(context, FloatWindowService.class));
            }
        } else {
            context.startService(new Intent(context, FloatWindowService.class));
        }
    }

    // 2. 添加异步翻译方法
    private void translateAsync(String input, TranslateCallback callback) {
        new Thread(() -> {
            String result;
            try {
                int otherLangIndex = homePrefs.getInt(OTHER_LANG_INDEX_KEY, 2); // 默认英语
                int myLangIndex = homePrefs.getInt(MY_LANG_INDEX_KEY, 0); // 默认简体中文
                String langJson = homePrefs.getString(LANG_CACHE_KEY, "[]");
                JSONArray arr = new JSONArray(langJson);
                String toLang  = arr.getJSONObject(otherLangIndex).getString("code");
                String fromLang = arr.getJSONObject(myLangIndex).getString("code");

                // 新增：如果源语言和目标语言相同，直接返回原文
                if (fromLang.equals(toLang)) {
                    new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
                        callback.onResult(input);
                    });
                    return;
                }

                Log.d("翻译服务", "allLanguages=" + langJson);
                Log.d("翻译服务", "otherLangIndex=" + otherLangIndex + ", myLangIndex=" + myLangIndex);
                Log.d("翻译服务", "请求参数: from=" + fromLang + ", to=" + toLang + ", text=" + input);
                
                // 获取服务器地址
                String serverUrl = getServerUrl();
                
                JSONObject req = new JSONObject();
                req.put("text", input);
                req.put("from_lang", fromLang);
                req.put("to_lang", toLang);
                URL url = new URL("http://" + serverUrl + "/translate");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setDoOutput(true);
                conn.getOutputStream().write(req.toString().getBytes());
                int code = conn.getResponseCode();
                StringBuilder sb = new StringBuilder();
                if (code == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) sb.append(line);
                    reader.close();
                    Log.d("翻译服务", "翻译响应: " + sb.toString());
                    JSONObject resp = new JSONObject(sb.toString());
                    if (resp.has("result") && resp.getJSONObject("result").has("trans_result")) {
                        result = resp.getJSONObject("result").getJSONObject("trans_result").optString("dst", "翻译失败");
                    } else {
                        result = "翻译失败";
                    }
                } else {
                    result = "翻译失败";
                }
            } catch (Exception e) {
                Log.e("翻译服务", "翻译异常", e);
                result = "翻译失败";
            }
            String finalResult = result;
            new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
                callback.onResult(finalResult);
            });
        }).start();
    }
    
    /**
     * 获取服务器地址
     */
    private String getServerUrl() {
        try {
            android.content.SharedPreferences prefs = getSharedPreferences("app_config", Context.MODE_PRIVATE);
            return prefs.getString("server_url", "qixin.yeshan.fun");
        } catch (Exception e) {
            Log.e("FloatWindowService", "获取服务器地址失败", e);
            return "qixin.yeshan.fun";
        }
    }
    
    // 3. 添加显示ASR结果的方法
    public void showAsrResult(String asrText) {
        new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
            // 优先用 currentMsgIndex
            int idx = currentMsgIndex;
            if (idx < 0 || idx >= messageList.size()) {
                // 尝试找到最后一个对方消息且内容为空的
                for (int i = messageList.size() - 1; i >= 0; i--) {
                    MessageAdapter.Message msg = messageList.get(i);
                    if (!msg.isMe && (msg.sourceText == null || msg.sourceText.isEmpty())) {
                        idx = i;
                        break;
                    }
                }
            }
            if (idx >= 0 && idx < messageList.size()) {
                MessageAdapter.Message msg = messageList.get(idx);
                msg.sourceText = asrText;
                messageAdapter.notifyItemChanged(idx);
                recyclerView.scrollToPosition(idx);
                lastAsrText = asrText;
                Log.d("FloatWindowService", "增量ASR内容: " + asrText);
            } else {
                // 没有可用消息就新建一条
                MessageAdapter.Message msg = new MessageAdapter.Message(false, asrText, "", false);
                messageList.add(msg);
                currentMsgIndex = messageList.size() - 1;
                messageAdapter.notifyItemInserted(currentMsgIndex);
                recyclerView.scrollToPosition(currentMsgIndex);
                lastAsrText = asrText;
                Log.d("FloatWindowService", "新建消息并写入ASR内容: " + asrText);
            }
        });
    }
    
    // 4. 添加发送TTS文本的方法
    private void sendTTSText(String text) {

        // 通过BleForegroundService发送TTS文本
        try {
            Log.d("FloatWindowService", "🎤 准备发送TTS广播: " + text);
            Intent intent = new Intent("com.smart.translator.TTS_SEND");
            intent.putExtra("text", text);
            // 使用LocalBroadcastManager发送本地广播
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            Log.d("FloatWindowService", "✅ TTS本地广播已发送: " + text);
        } catch (Exception e) {
            Log.e("FloatWindowService", "❌ 发送TTS文本失败", e);
        }
//        if (ttsPlayer != null && ttsPlayer.isConnected()) {
//            // 默认使用自动选择模式（耳机优先）
//            ttsPlayer.setAudioOutputMode(SimpleWebSocketTTSPlayer.AUDIO_OUTPUT_AUTO);
//            ttsPlayer.sendText(text);
//        } else {
//            Toast.makeText(this, "TTS未连接", Toast.LENGTH_SHORT).show();
//        }
    }
    
    // 添加带音频输出模式的TTS发送方法
    private void sendTTSText(String text, int audioOutputMode) {
        if (ttsPlayer != null && ttsPlayer.isConnected()) {
            ttsPlayer.setAudioOutputMode(audioOutputMode);
            ttsPlayer.sendText(text);
        } else {
            Toast.makeText(this, "TTS未连接", Toast.LENGTH_SHORT).show();
        }
    }

    private void registerAsrReceiver() {
        // 使用LocalBroadcastManager注册接收器
        asrReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // 确保在主线程中处理
                new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
                    Log.d("FloatWindowService", "📡 LocalBroadcastManager接收器被调用，Action: " + intent.getAction());
                    
                    // 新增：获取asr_provider类型
                    String asrProvider = "doubao";
                    try {
                        SharedPreferences prefs = getSharedPreferences("app_config", Context.MODE_PRIVATE);
                        asrProvider = prefs.getString("asr_provider", "doubao");
                    } catch (Exception e) {
                        Log.e("FloatWindowService", "获取asr_provider失败", e);
                    }

                    if ("com.smart.translator.ASR_RESULT".equals(intent.getAction())) {
                        String asrText = intent.getStringExtra("asr_text");
                        boolean isVadFinal = intent.getBooleanExtra("is_vad_final", false);
                        boolean isVosk = intent.getBooleanExtra("is_vosk", false);
                        Log.d("FloatWindowService", "📡 收到ASR结果数据: " + asrText + ", VAD最终: " + isVadFinal + ", Vosk: " + isVosk);
                        
                        if (asrText != null && !asrText.isEmpty()) {
                            if (isVosk) {
                                // Vosk离线识别结果，在语音转文本标签页显示
                                Log.d("FloatWindowService", "🎯 收到Vosk离线识别结果，在语音转文本标签页显示");
                                showVoskResult(asrText, intent.getBooleanExtra("is_vad_final", false));
                            } else if ("aliyun".equals(asrProvider)) {
                                boolean isCloudFinal = intent.getBooleanExtra("is_cloud_final", false); // 由BleForegroundService广播传递
                                if (isCloudFinal) {
                                    Log.d("FloatWindowService", "Aliyun is_cloud_final==true，显示最终消息: " + asrText);
                                    // 直接在主线程处理，避免额外的Handler延迟
                                    showAsrFinalResultDirect(asrText);
                                    showStatus("识别完成");
                                    if (asrWaitRunnableTab1 != null) asrWaitHandlerTab1.removeCallbacks(asrWaitRunnableTab1);
                                } else {
                                    Log.d("FloatWindowService", "Aliyun is_cloud_final==false，忽略该消息: " + asrText);
                                    return;
                                }
                            } else {
                                // doubao等其他ASR类型，维持原有VAD逻辑
                                Log.d("FloatWindowService", "📡 LocalBroadcastManager收到豆包/其他ASR结果: " + asrText);
                                if (isVadFinal) {
                                    Log.d("FloatWindowService", "🎯 收到VAD最终结果，调用showVadFinalResult");
                                    showVadFinalResult(asrText);
                                } else {
                                    Log.d("FloatWindowService", "📝 收到普通增量结果，调用showAsrResult");
                                    showAsrResult(asrText);
                                }
                            }
                        } else {
                            Log.w("FloatWindowService", "❌ ASR结果数据为空");
                        }
                    }
                });
            }
        };
        
        IntentFilter filter = new IntentFilter("com.smart.translator.ASR_RESULT");
        LocalBroadcastManager.getInstance(this).registerReceiver(asrReceiver, filter);
        Log.d("FloatWindowService", "📡 LocalBroadcastManager ASR接收器已注册");
    }

    // 新增：显示VAD最终结果的方法
    public void showVadFinalResult(String asrText) {
        new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
            Log.d("FloatWindowService", "🎯 开始处理VAD最终结果: " + asrText);
            Log.d("FloatWindowService", "当前状态 - currentMsgIndex: " + currentMsgIndex + ", messageList.size: " + messageList.size());
            
            // 添加空指针检查
            if (messageAdapter == null) {
                Log.w("FloatWindowService", "messageAdapter为null，跳过VAD最终结果显示");
                return;
            }
            
            // 检查是否为阿里云ASR，如果是则跳过VAD最终结果处理
            String asrProvider = "doubao";
            try {
                SharedPreferences prefs = getSharedPreferences("app_config", Context.MODE_PRIVATE);
                asrProvider = prefs.getString("asr_provider", "doubao");
            } catch (Exception e) {
                Log.e("FloatWindowService", "获取asr_provider失败", e);
            }
            
            if ("aliyun".equals(asrProvider)) {
                Log.d("FloatWindowService", "阿里云ASR，跳过VAD最终结果处理，避免与阿里云结果冲突");
                return;
            }
            
            // VAD最终结果，直接显示完整内容，不受说话状态影响
            if (currentMsgIndex >= 0 && currentMsgIndex < messageList.size()) {
                MessageAdapter.Message msg = messageList.get(currentMsgIndex);
                msg.sourceText = asrText; // 直接设置完整内容
                msg.isSpeaking = false; // 移除红点
                messageAdapter.notifyItemChanged(currentMsgIndex);
                recyclerView.scrollToPosition(currentMsgIndex);
                lastAsrText = asrText;
                lastFinalAsrText = asrText; // 更新最终内容
                Log.d("FloatWindowService", "✅ VAD最终结果已更新到现有消息: " + asrText);
            } else {
                // 如果没有当前消息，检查是否有最后一条对方消息可以更新
                if (!messageList.isEmpty()) {
                    MessageAdapter.Message lastMsg = messageList.get(messageList.size() - 1);
                    if (!lastMsg.isMe) {
                        // 更新最后一条对方消息
                        lastMsg.sourceText = asrText;
                        lastMsg.isSpeaking = false;
                        messageAdapter.notifyItemChanged(messageList.size() - 1);
                        recyclerView.scrollToPosition(messageList.size() - 1);
                        lastAsrText = asrText;
                        lastFinalAsrText = asrText;
                        Log.d("FloatWindowService", "✅ VAD最终结果已更新到最后消息: " + asrText);
                        return;
                    }
                }
                
                // 如果确实没有可更新的消息，才创建新的
                MessageAdapter.Message msg = new MessageAdapter.Message(false, asrText, "", false);
                messageList.add(msg);
                currentMsgIndex = messageList.size() - 1;
                messageAdapter.notifyItemInserted(currentMsgIndex);
                recyclerView.scrollToPosition(currentMsgIndex);
                lastAsrText = asrText;
                lastFinalAsrText = asrText;
                Log.d("FloatWindowService", "✅ VAD最终结果已创建新消息: " + asrText);
            }
            currentMsgIndex = -1; // 只在最终结果时重置
        });
    }

    // 新增：显示Vosk离线识别结果的方法
    public void showVoskResult(String voskText, boolean isFinal) {
        new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
            Log.d("FloatWindowService", "🎯 Tab3处理Vosk识别结果: " + voskText + ", 最终: " + isFinal);
            if (messageAdapterVosk == null) return;
            
            // 如果识别结果为空，不处理
            if (voskText == null || voskText.trim().isEmpty()) {
                Log.d("FloatWindowService", "Vosk识别结果为空，跳过处理");
                return;
            }
            
            // 优先更新现有的消息，避免创建重复消息
            if (currentMsgIndexVosk >= 0 && currentMsgIndexVosk < messageListVosk.size()) {
                // 更新现有的消息
                MessageAdapter.Message msg = messageListVosk.get(currentMsgIndexVosk);
                Log.d("FloatWindowService", "🔍 更新现有消息 - 索引: " + currentMsgIndexVosk + ", 原内容: '" + msg.sourceText + "', 新内容: '" + voskText + "'");
                msg.sourceText = voskText;
                if (isFinal) {
                    msg.isSpeaking = false; // 最终结果时移除红点
                    currentMsgIndexVosk = -1; // 最终结果处理完成后重置索引
                    Log.d("FloatWindowService", "✅ Vosk最终结果已更新现有消息: " + voskText);
                } else {
                    msg.isSpeaking = true; // 部分结果时保持红点
                    Log.d("FloatWindowService", "📝 Vosk部分结果已更新现有消息: " + voskText);
                }
                // 使用更强制性的刷新方式
                messageAdapterVosk.notifyDataSetChanged();
                recyclerViewVosk.scrollToPosition(currentMsgIndexVosk);
                // 强制重新布局
                recyclerViewVosk.requestLayout();
                Log.d("FloatWindowService", "🔄 已通知适配器更新消息，当前消息列表大小: " + messageListVosk.size());
            } else {
                // 检查最后一条消息是否是空白消息（VAD创建的）
                if (!messageListVosk.isEmpty()) {
                    MessageAdapter.Message lastMsg = messageListVosk.get(messageListVosk.size() - 1);
                    Log.d("FloatWindowService", "🔍 检查最后一条消息 - 内容: '" + lastMsg.sourceText + "', 正在说话: " + lastMsg.isSpeaking);
                    if (lastMsg.sourceText.isEmpty() && !lastMsg.isSpeaking) {
                        // 更新最后一条空白消息
                        lastMsg.sourceText = voskText;
                        if (isFinal) {
                            lastMsg.isSpeaking = false; // 最终结果时移除红点
                            currentMsgIndexVosk = -1; // 最终结果处理完成后重置索引
                            Log.d("FloatWindowService", "✅ Vosk最终结果已更新最后一条空白消息: " + voskText);
                        } else {
                            lastMsg.isSpeaking = true; // 部分结果时保持红点
                            currentMsgIndexVosk = messageListVosk.size() - 1;
                            Log.d("FloatWindowService", "📝 Vosk部分结果已更新最后一条空白消息: " + voskText);
                        }
                        // 使用更强制性的刷新方式
                        messageAdapterVosk.notifyDataSetChanged();
                        recyclerViewVosk.scrollToPosition(messageListVosk.size() - 1);
                        // 强制重新布局
                        recyclerViewVosk.requestLayout();
                        Log.d("FloatWindowService", "🔄 已通知适配器更新最后一条消息");
                        return;
                    }
                }
                
                // 只有在没有现有消息时才创建新消息
                MessageAdapter.Message msg = new MessageAdapter.Message(false, voskText, "", !isFinal);
                messageListVosk.add(msg);
                currentMsgIndexVosk = messageListVosk.size() - 1;
                // 使用更强制性的刷新方式
                messageAdapterVosk.notifyDataSetChanged();
                recyclerViewVosk.scrollToPosition(currentMsgIndexVosk);
                // 强制重新布局
                recyclerViewVosk.requestLayout();
                if (isFinal) {
                    currentMsgIndexVosk = -1; // 最终结果处理完成后重置索引
                    Log.d("FloatWindowService", "✅ Vosk最终结果已创建新消息: " + voskText);
                } else {
                    Log.d("FloatWindowService", "🆕 Vosk部分结果已创建新消息: " + voskText);
                }
            }
            
            // 调试：检查整个消息列表的内容
            Log.d("FloatWindowService", "📋 当前消息列表内容:");
            for (int i = 0; i < messageListVosk.size(); i++) {
                MessageAdapter.Message msg = messageListVosk.get(i);
                Log.d("FloatWindowService", "  消息[" + i + "]: 内容='" + msg.sourceText + "', 正在说话=" + msg.isSpeaking + ", 是我=" + msg.isMe);
            }
        });
    }

    // 新增：设置对方正在讲话提示
    private void setPeerSpeaking(boolean speaking) {
        Log.d("FloatWindowService", "🎤 设置对方说话状态: " + speaking + ", 当前状态: " + isPeerSpeaking);
        isPeerSpeaking = speaking;
        if (layoutPeerSpeaking != null) {
            layoutPeerSpeaking.setVisibility(View.GONE); // 不再用全局提示
        }
        
        // 添加空指针检查，防止崩溃
        if (messageAdapter == null) {
            Log.w("FloatWindowService", "messageAdapter为null，跳过说话状态设置");
            return;
        }
        
        if (speaking) {
            // 说话开始，新建一条对方消息，带红点
            MessageAdapter.Message msg = new MessageAdapter.Message(false, "", "", true);
            messageList.add(msg);
            currentMsgIndex = messageList.size() - 1;
            messageAdapter.notifyItemInserted(currentMsgIndex);
            recyclerView.scrollToPosition(currentMsgIndex);
            lastAsrText = "";
            // 说话开始时，不要动lastFinalAsrText
            Log.d("FloatWindowService", "🎤 说话开始，创建新消息，currentMsgIndex: " + currentMsgIndex);
        } else {
            // 说话结束，只移除红点，不设置内容（内容由ASR最终结果设置）
            if (currentMsgIndex >= 0 && currentMsgIndex < messageList.size()) {
                MessageAdapter.Message msg = messageList.get(currentMsgIndex);
                msg.isSpeaking = false;
                // 不在这里设置sourceText，让ASR最终结果来处理
                messageAdapter.notifyItemChanged(currentMsgIndex);
                // 不在这里更新lastFinalAsrText，让ASR最终结果来处理
                Log.d("FloatWindowService", "🔇 说话结束，移除红点，等待ASR最终结果");
                // 注意：不要在这里重置currentMsgIndex，让阿里云ASR结果能够更新现有消息
            } else {
                Log.w("FloatWindowService", "🔇 说话结束，但currentMsgIndex无效: " + currentMsgIndex);
            }
        }
    }

    // Tab3的VAD提示逻辑
    private void setPeerSpeakingVosk(boolean speaking) {
        isPeerSpeakingVosk = speaking;
        // 移除顶部区域的"正在讲话"提示，只在消息左边显示红点
        // if (layoutPeerSpeakingVosk != null) {
        //     layoutPeerSpeakingVosk.setVisibility(speaking ? View.VISIBLE : View.GONE);
        // }
        
        if (speaking) {
            // 说话开始，创建一个带红点的空白消息
            MessageAdapter.Message msg = new MessageAdapter.Message(false, "", "", true);
            messageListVosk.add(msg);
            currentMsgIndexVosk = messageListVosk.size() - 1;
            // 使用更强制性的刷新方式
            messageAdapterVosk.notifyDataSetChanged();
            recyclerViewVosk.scrollToPosition(currentMsgIndexVosk);
            // 强制重新布局
            recyclerViewVosk.requestLayout();
            Log.d("FloatWindowService", "🎤 Vosk VAD检测到语音开始，创建带红点的消息，currentMsgIndexVosk: " + currentMsgIndexVosk);
        } else {
            // 说话结束，只移除红点，不重置currentMsgIndexVosk，让识别结果能够更新现有消息
            if (currentMsgIndexVosk >= 0 && currentMsgIndexVosk < messageListVosk.size()) {
                MessageAdapter.Message msg = messageListVosk.get(currentMsgIndexVosk);
                msg.isSpeaking = false;
                // 使用更强制性的刷新方式
                messageAdapterVosk.notifyDataSetChanged();
                // 强制重新布局
                recyclerViewVosk.requestLayout();
                Log.d("FloatWindowService", "🔇 Vosk VAD检测到语音结束，移除红点，保持currentMsgIndexVosk: " + currentMsgIndexVosk);
            } else {
                Log.d("FloatWindowService", "🔇 Vosk VAD检测到语音结束，但没有找到当前消息");
            }
            // 不要在这里设置 currentMsgIndexVosk = -1，让识别结果能够更新现有消息
        }
    }

    // 新增：设置TTS播放状态显示
    private void setTtsPlaying(boolean playing, String text) {
        Log.d("FloatWindowService", "🔊 设置TTS播放状态: " + playing + ", 文本: " + text);
        isTtsPlaying = playing;
        currentTtsText = text;
        
        if (layoutTtsPlaying != null && tvTtsPlaying != null) {
            if (playing && !text.isEmpty()) {
                layoutTtsPlaying.setVisibility(View.VISIBLE);
                tvTtsPlaying.setText("正在播放: " + text);
            } else {
                layoutTtsPlaying.setVisibility(View.GONE);
            }
        }
    }

    // 新增：注册VAD说话状态广播
    private void registerVadStateReceiver() {
        BroadcastReceiver vadReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("com.smart.translator.VAD_STATE".equals(intent.getAction())) {
                    boolean speaking = intent.getBooleanExtra("is_speaking", false);
                    setPeerSpeaking(speaking);         // 只影响Tab1（无障碍通话）
                }
            }
        };
        IntentFilter filter = new IntentFilter("com.smart.translator.VAD_STATE");
        LocalBroadcastManager.getInstance(this).registerReceiver(vadReceiver, filter);
    }

    // 新增：注册Vosk VAD说话状态广播
    private void registerVoskVadStateReceiver() {
        BroadcastReceiver voskVadReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("com.smart.translator.VOSK_VAD_STATE".equals(intent.getAction())) {
                    boolean speaking = intent.getBooleanExtra("is_speaking", false);
                    setPeerSpeakingVosk(speaking);
                }
            }
        };
        IntentFilter filter = new IntentFilter("com.smart.translator.VOSK_VAD_STATE");
        LocalBroadcastManager.getInstance(this).registerReceiver(voskVadReceiver, filter);
        Log.d("FloatWindowService", "📡 Vosk VAD状态广播接收器已注册");
    }

    // 新增：上传TTS统计数据
    private void uploadTtsStats(int textLength) {
        try {
            UserManager userManager = UserManager.getInstance(this);
            if (!userManager.hasValidUserId()) {
                Log.w("FloatWindowService", "用户未登录或用户ID无效，跳过上传TTS统计");
                return;
            }

            int userId = userManager.getUserId();
            Log.d("FloatWindowService", "准备上传TTS统计数据 - 用户ID: " + userId + ", 文本长度: " + textLength);

            // 调用统计API服务
            CompletableFuture<ApiResponse<String>> statsFuture = StatsApiService.uploadStats(this, userId, textLength);
            statsFuture.thenAcceptAsync(response -> {
                if (response.isSuccess()) {
                    Log.d("FloatWindowService", "TTS统计数据上传成功: " + response.getData());
                } else {
                    Log.e("FloatWindowService", "TTS统计数据上传失败: " + response.getError());
                }
            }).exceptionally(throwable -> {
                Log.e("FloatWindowService", "TTS统计数据上传异常", throwable);
                return null;
            });

        } catch (Exception e) {
            Log.e("FloatWindowService", "上传TTS统计数据失败", e);
        }
    }

    // showStatus方法示例（复用tv_peer_speaking）
    private void showStatus(String status) {
        // 确保在主线程中执行UI更新
        new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
            // 复用Tab1顶部的对方正在讲话TextView
            TextView tvStatus = floatView.findViewById(R.id.tv_peer_speaking);
            if (tvStatus != null) {
                tvStatus.setText(status);
                tvStatus.setVisibility(View.VISIBLE);
                // 保证父布局可见
                View parent = (View) tvStatus.getParent();
                if (parent != null) parent.setVisibility(View.VISIBLE);
            }
        });
    }

    // 新增：只用于Aliyun最终结果的显示，每次都新建一条消息用于Aliyun最终结果显示，并在Aliyun ASR只在最终结果时调用此方法。
    public void showAsrFinalResult(String asrText) {
        new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
            Log.d("FloatWindowService", "🎯 开始处理Aliyun最终结果: " + asrText);
            
            // 添加去重检查，防止重复处理相同的ASR结果
            if (asrText.equals(lastAliyunAsrText)) {
                Log.d("FloatWindowService", "🔄 阿里云ASR结果重复，跳过处理: " + asrText);
                return;
            }
            lastAliyunAsrText = asrText;
            
            // 添加空指针检查
            if (messageAdapter == null) {
                Log.w("FloatWindowService", "messageAdapter为null，跳过Aliyun最终结果显示");
                return;
            }
            
            // 优先查找现有的空消息进行更新，避免重复创建
            int targetIndex = -1;
            
            // 1. 首先检查currentMsgIndex是否有效
            if (currentMsgIndex >= 0 && currentMsgIndex < messageList.size()) {
                MessageAdapter.Message msg = messageList.get(currentMsgIndex);
                if (!msg.isMe && (msg.sourceText == null || msg.sourceText.isEmpty())) {
                    targetIndex = currentMsgIndex;
                    Log.d("FloatWindowService", "🔍 找到currentMsgIndex对应的空消息: " + targetIndex);
                }
            }
            
            // 2. 如果currentMsgIndex无效，查找最后一个空消息
            if (targetIndex == -1) {
                for (int i = messageList.size() - 1; i >= 0; i--) {
                    MessageAdapter.Message msg = messageList.get(i);
                    if (!msg.isMe && (msg.sourceText == null || msg.sourceText.isEmpty())) {
                        targetIndex = i;
                        Log.d("FloatWindowService", "🔍 找到最后一个空消息: " + targetIndex);
                        break;
                    }
                }
            }
            
            // 3. 如果找到现有消息，更新它
            if (targetIndex >= 0 && targetIndex < messageList.size()) {
                MessageAdapter.Message msg = messageList.get(targetIndex);
                msg.sourceText = asrText;
                msg.isSpeaking = false; // 移除红点
                
                // 使用notifyItemChanged而不是notifyDataSetChanged，提高性能
                messageAdapter.notifyItemChanged(targetIndex);
                recyclerView.scrollToPosition(targetIndex);
                
                lastAsrText = asrText;
                currentMsgIndex = -1; // 重置索引
                Log.d("FloatWindowService", "✅ Aliyun最终结果已更新到现有消息: " + asrText);
            } else {
                // 4. 只有在没有可更新的消息时才创建新消息
                MessageAdapter.Message msg = new MessageAdapter.Message(false, asrText, "", false);
                messageList.add(msg);
                int newIndex = messageList.size() - 1;
                
                // 使用notifyItemInserted而不是notifyDataSetChanged，提高性能
                messageAdapter.notifyItemInserted(newIndex);
                recyclerView.scrollToPosition(newIndex);
                
                lastAsrText = asrText;
                currentMsgIndex = -1; // 重置索引
                Log.d("FloatWindowService", "🆕 Aliyun最终结果已创建新消息: " + asrText);
            }
        });
    }

    // 新增：直接在主线程处理Aliyun最终结果，避免额外的Handler延迟
    private void showAsrFinalResultDirect(String asrText) {
        // 添加去重检查，防止重复处理相同的ASR结果
        if (asrText.equals(lastAliyunAsrText)) {
            return;
        }
        lastAliyunAsrText = asrText;
        
        // 添加空指针检查
        if (messageAdapter == null) {
            return;
        }
        
        // 优先查找现有的空消息进行更新，避免重复创建
        int targetIndex = -1;
        
        // 1. 首先检查currentMsgIndex是否有效
        if (currentMsgIndex >= 0 && currentMsgIndex < messageList.size()) {
            MessageAdapter.Message msg = messageList.get(currentMsgIndex);
            if (!msg.isMe && (msg.sourceText == null || msg.sourceText.isEmpty())) {
                targetIndex = currentMsgIndex;
            }
        }
        
        // 2. 如果currentMsgIndex无效，查找最后一个空消息
        if (targetIndex == -1) {
            for (int i = messageList.size() - 1; i >= 0; i--) {
                MessageAdapter.Message msg = messageList.get(i);
                if (!msg.isMe && (msg.sourceText == null || msg.sourceText.isEmpty())) {
                    targetIndex = i;
                    break;
                }
            }
        }
        
        // 3. 如果找到现有消息，更新它
        if (targetIndex >= 0 && targetIndex < messageList.size()) {
            MessageAdapter.Message msg = messageList.get(targetIndex);
            msg.sourceText = asrText;
            msg.isSpeaking = false; // 移除红点
            
            // 使用notifyItemChanged而不是notifyDataSetChanged，提高性能
            messageAdapter.notifyItemChanged(targetIndex);
            recyclerView.scrollToPosition(targetIndex);
            
            lastAsrText = asrText;
            currentMsgIndex = -1; // 重置索引
        } else {
            // 4. 只有在没有可更新的消息时才创建新消息
            MessageAdapter.Message msg = new MessageAdapter.Message(false, asrText, "", false);
            messageList.add(msg);
            int newIndex = messageList.size() - 1;
            
            // 使用notifyItemInserted而不是notifyDataSetChanged，提高性能
            messageAdapter.notifyItemInserted(newIndex);
            recyclerView.scrollToPosition(newIndex);
            
            lastAsrText = asrText;
            currentMsgIndex = -1; // 重置索引
        }
    }

    // 新增：发送悬浮窗状态变更广播
    private void sendFloatWindowStatusBroadcast(boolean show) {
        Intent intent = new Intent("com.smart.translator.FLOAT_WINDOW_STATUS_CHANGED");
        intent.putExtra("show", show);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        Log.d("FloatWindowService", "已发送悬浮窗状态广播，show=" + show);
    }
} 